<?php 
    drupal_add_js("http://js.api.here.com/se/2.5.4/jsl.js?with=all",'external');
    drupal_add_js(JS . "text-on-icon-marker.js",'external'); //Let here map marker support custom icon and text
    drupal_add_html_head(array("#tag"=> "meta","#attributes"=> array("http-equiv"=>"X-UA-Compatible","content"=>"IE=7; IE=EmulateIE9; IE=10")), 'here_map_ie_compatible');//Come from http://developer.here.com/get-started
    drupal_add_css(CSS . 'search_result.css',array("type"=>"external"));
    $lan = get_lan();
    require_once(LANG.$lan."/map.php");//Alway using this pattern to locate language dependent static content.
?>
        <script>
        var $;
        var MAP; // Here map display instance
        var VISTABLE_MARKER = [];//Array for enabled marker
        var MARKER_CONTAINER;//Here map object container for marker
        var BUBBLES;//Global const for keep here map bubble popup
		var MAX_PAGE =[];//Array for keep max page of each categories 
        var CURRENT_PAGE = [];//Array for keep currently display page of each categories
        var category_selected = 1;//Current selected category
        var RELOAD_FUNC = [];//On page change / filtering(Refresh content) , It will invoked , each item of array should be array contain refresh content function and filter function
        var FILTER_FUNC = [];//List of function that will return filter data of each categories
        var LAN = "<?=$lan?>";//Current language
        var DEUPAL_BASE = "<?=$GLOBALS['base_url']?>";//Drupal path
        var SEARCH_KEY = "<?=!empty($city)?$city:$country?>";//User search keyword for reconstruct link.
        function optimum_zoom_level()
        {
            /*
            *   Function name       Purpose
            *   optimum_zoom_level  set map to maximum zoom level that can visible all marker 
            *
            *
            */
            var c_box = MARKER_CONTAINER.getBoundingBox();
            /*
            bounding box of container should be computed similar below:
            var min_lat,min_long,max_lat,max_long;
            min_lat=min_long=999;
            max_long=max_lat=-999;
            for (var i =0;i< VISTABLE_MARKER.length;i++)
            {
                
                var marker_cood = VISTABLE_MARKER[i].coordinate;
                if (marker_cood.latitude > max_lat)
                {
                    max_lat = marker_cood.latitude;
                }
                if (marker_cood.latitude < min_lat)
                {
                    min_lat = marker_cood.latitude;
                }
                if (marker_cood.longitude > max_long)
                {
                    max_long = marker_cood.longitude;
                }
                if (marker_cood.longitude < min_long)
                {
                    min_long = marker_cood.longitude;
                }
            }
            var makrers_bbox = new nokia.maps.geo.BoundingBox(new nokia.maps.geo.Coordinate(max_lat,min_long),new nokia.maps.geo.Coordinate(min_lat,max_long));//First one topleft , other one is bottom right of bbox  http://api.maps.nokia.com/en/apireference/2.2.0/symbols/nokia.maps.geo.BoundingBox.html , max longitude alway place into bottomRight
            */
            var optimum_zoom_level = (MAP.getBestZoomLevel([c_box]) - 1)< MAP.get("minZoomLevel")? MAP.get("minZoomLevel"):(MAP.getBestZoomLevel([c_box]) - 1);//since best zoom potentially let marker just view partially , we zoom out one level to avoid effect. getBestZoomLevel is build in function 
            MAP.setCenter(c_box.getCenter()); //(min+max)/2 = center
            MAP.setZoomLevel(optimum_zoom_level,"default");//change zoom level with default animation
            MAP.update();//Just confirm map will updated.
        }
        function update_page_status()
        {
            /*
            *   Function name       Purpose
            *   update_page_status  Update page button display , currently page and maximum page.
            */
            $("#current_page_status").html(CURRENT_PAGE[category_selected]);
            $("#max_page_status").html(MAX_PAGE[category_selected]);
        }
        function update_btn_status()
        {
            /*
            *   Function name   Purpose
            *   update
            *
            */
            if (CURRENT_PAGE[category_selected] == MAX_PAGE[category_selected])
            {
                $("#move_right").addClass("disabled");
            }
            else
            {
                $("#move_right").removeClass("disabled");
            }
            if (CURRENT_PAGE[category_selected] == 1)
            {
                $("#move_left").addClass("disabled");
            }
            else
            {
                $("#move_left").removeClass("disabled");
            }
        }
        function map_refresh(entities,popup_message_func)
        {
            if (popup_message_func === undefined){popup_message_func = function(entity)
            {
                    return "<div>" + entity.EntityName + "</div>";
            }
            }
            for (var i=0;i < VISTABLE_MARKER.length;i++)
            {
                MARKER_CONTAINER.objects.remove(VISTABLE_MARKER[i]);
            }
            VISTABLE_MARKER.length = 0;
            for (var i=0;i < entities.length;i++)
            {
            
                var entity = entities[i];
                //console.log(entity);
                var marker = new TextOnIconMarker([parseFloat(entity.EntityLatitude),parseFloat(entity.EntityLongitude)],{icon:"/res/img/search_result/landmark_map_gray.png",visibility:true,anchor:new nokia.maps.util.Point(31,38)});
                //marker.set("text",""+(i+1 + ((CURRENT_PAGE[category_selected]-1) * PAGE_SIZE ))+"");
                marker.set("text",""+(i+1));
                //var marker = new nokia.maps.map.StandardMarker([parseFloat(entity.EntityLatitude),parseFloat(entity.EntityLongitude)],{text:""+(i+1 + ((CURRENT_PAGE[category_selected]-1) * PAGE_SIZE ))+"",brush:{"color":"#AAAAAA"}});
                marker.addListener("click",function(event)
                {
                    BUBBLES.openBubble(popup_message_func(entity),event.target.coordinate);
                });
                
                VISTABLE_MARKER.push(marker);
                MARKER_CONTAINER.objects.add(marker);
            }
            optimum_zoom_level();
        }
        function onWinResize(e)
        {
            var top_pos = $("#slide_btn_wrap").position().top + $("#slide_btn_wrap").height();
            //console.log($("#fixed_content").position().top);
            //console.log($("#fixed_content").height());
            //$("#content_container").offset({top:top_pos,left:0});
            $("#content_container").css("top",top_pos+"px");
            //
            //console.log($("#content_container").position().top+$("#content_container").height());
            $(".body_wrap").height($("#content_container").position().top+$("#content_container").height());
            //$("#map_footer").css("top",$("#fixed_content").height()+"px");
            
        }
        function on_switch_page(e)
        {
            var next_page = CURRENT_PAGE[category_selected];
            //console.log($(this)[0] == $("#move_right")[0]);
            if ($(this)[0] == $("#move_left")[0])
            {
                next_page-=1;
            }
            else if ($(this)[0] == $("#move_right")[0])
            {
                next_page+=1;
            }
            else
            {
                next_page = 1;
            }
            $(".loading").show();
            //console.log("Go to page " + next_page +" of " + category_selected);
            var request_data = FILTER_FUNC[category_selected]();
            request_data.location = "<?=$request_location?>";
            request_data.page = next_page;
            request_data.trigger_category = category_selected;
            var request = $.ajax("/controller/entity_filtering.php",
            {
                dataType:"json",
                data:request_data,
                //async :false
            });
            request.done(function(data)
            {
                
                CURRENT_PAGE[category_selected] = next_page;
                MAX_PAGE[category_selected]=data.Records[0][0][2];
                update_btn_status();
                update_page_status();
                var visual_container = $("#entity_content");
                var filter_container = $("#filter_box");
                var containers = [visual_container,filter_container];
                var contin = true;
                if (RELOAD_FUNC[category_selected][1])
                {
                    if (RELOAD_FUNC[category_selected][1](data,filter_container) !== undefined)
                    {
                        contin = false;
                    }
                }
                if (contin)
                {
                    RELOAD_FUNC[category_selected][0](data,visual_container);
                    $(".loading").hide();
                }
            });
            request.fail(function(jqXHR, textStatus)
            {
                console.log(jqXHR);
                console.log(textStatus);
            });
        }
        
        jQuery(document).ready(function()
        {
            
            $ = jQuery.noConflict();
            change_box_value("<?=$request_location?>");
            nokia.Settings.set("app_id", "<?=$map_id?>");
            nokia.Settings.set("app_code","<?=$map_key?>");
            BUBBLES = new nokia.maps.map.component.InfoBubbles();
            MARKER_CONTAINER = new nokia.maps.map.Container();
            <?php
                foreach ($categories_data as $index=>$category)
                {
                        if ($category["Total"] > 0){
                    ?>
                        
                        MAX_PAGE[<?=$category["Category_ID"]?>] =  <?=$category["Records"][0][0][2]?>;
                        CURRENT_PAGE[<?=$category["Category_ID"]?>] = 1;
                    <?php
                        }
                }
                    foreach ($categories_data[0]["Records"][0][0][0] as $index=>$hotel)
                    {
            ?>
                        //var marker = new nokia.maps.map.Marker([<?=$hotel["EntityLatitude"]?>,<?=$hotel["EntityLongitude"]?>],{text:"<?=$index+1?>",icon:"/res/img/search_result/landmark_map_gray.png",visibility:true,anchor:new nokia.maps.util.Point(31,38),title:"12345"});
                        //var marker = new nokia.maps.map.StandardMarker([<?=$hotel["EntityLatitude"]?>,<?=$hotel["EntityLongitude"]?>],{text:"<?=$index+1?>",brush:{"color":"#AAAAAA"}});
                        var marker = new TextOnIconMarker([<?=$hotel["EntityLatitude"]?>,<?=$hotel["EntityLongitude"]?>],{icon:"/res/img/search_result/landmark_map_gray.png",visibility:true,anchor:new nokia.maps.util.Point(31,38)});
                        marker.set("text","<?=$index+1?>");
                        //marker.set("textPen",{"color":"#AAAAAA"});
                        //marker.text_color = "#FF0000";
                        marker.addListener("click",function(event)
                        {
                            BUBBLES.openBubble("<div><?=$hotel["EntityName"]?></div>",event.target.coordinate);
                           
                        });
                        VISTABLE_MARKER.push(marker);
                        MARKER_CONTAINER.objects.add(marker);
            <?php
                    }
            ?>
            MAP = new nokia.maps.map.Display(
        	document.getElementById("mapContainer"), 
            {
                components: [
				new  nokia.maps.map.component.Behavior(),
                    BUBBLES,
                    new nokia.maps.map.component.ZoomBar()
                    ],
        		// Map center coordinates
        		center: [0.0,0.0]
        	}
        );
            MAP.addListener("displayready",function(e)
            {
                MAP.objects.add(MARKER_CONTAINER);
                optimum_zoom_level();
                /*After compute content block position , open first tab to user.*/
                $("#categories_id a:first").tab("show");
                /*Until map is loaded , we need compute the content block position*/
                $(window).resize();
            }
                
            )
           $(window).resize(onWinResize);
           $(window).scroll(function(e)
           {
            if ($(this).scrollTop() > 0)
            {
                $(".back2Top").show();
            }
            else
            {
                $(".back2Top").hide();
            }
            if ($(this).scrollTop() >= $("#header_bar").height())
            {
                $("#fixed_content").css("top","0px");
                //$(window).resize();
            }
            else if ($(this).scrollTop()>0)
            {
                var pos = $("#header_bar").height() - $(this).scrollTop();
                //console.log(pos);
                $("#fixed_content").css("top",pos+"px");
                //$(window).resize();
            }
            else
            {
                 $("#fixed_content").css("top","");
                 //$(window).resize();
            }
           }
           )
           /*Switch page handle*/
           $("#move_left").click(on_switch_page);
           $("#move_right").click(on_switch_page);
           /*On tab change*/
           $("#categories_id a").click
           (
            function(e)
            {
                /*Using category_index to access max page of current category*/
                if (category_selected != $(this).attr("category_index"))
                {
                    category_selected = $(this).attr("category_index");
                    update_btn_status();
                }
                //console.log($(this).attr("category_index"));
                //console.log($(this).index());
            }
           )
           $("#back2Top").click(function(e)
           {
                window.scrollTo(0,0);
           }
           )
           /*Prevent close the menu on click menu . Stop the bubble event passing*/
           /*
           $("#filter_box").click(function(e){
           //e.stopPropagation();
           });
           */
           $("#slide_btn").click
           (
            function(e)
            {
                e.preventDefault();
                var btn_dom = $(this);
                
                //if (MAP_STATUS == 0)
                if ($("#map_content").is(":visible"))
                {
                    $("#map_content").slideUp("slow",function(){
                    $(window).resize();
                    //$("#slide_btn span:first").attr("class","glyphicon glyphicon-arrow-down");
                    btn_dom.parent().removeClass("slide_btn_s1");
                    btn_dom.parent().addClass("slide_btn_s2");
                    }
                    );
                }
                else
                {
                    $("#map_content").slideDown("slow",function(){
                    $(window).resize();
                    //$("#slide_btn span:first").attr("class","glyphicon glyphicon-arrow-up")
                    btn_dom.parent().removeClass("slide_btn_s2");
                    btn_dom.parent().addClass("slide_btn_s1");
                    });
                    
                }
            }
           )
        }
        
        )

        </script>
        <div class="center-block body_wrap">
        <div class="back2Top" style="display:none" id="back2Top"><img src="<?=$top_img?>"></div>
        <div class="loading" style="display:none"><img src="/res/img/loading.gif"></img></div>
        <div class="header_bar" id="header_bar">
            <span class="logo">
                <?php if ($logo): ?>
                    <a href="<?php print $front_page; ?>" title="<?php print t('Home'); ?>" rel="home" id="logo"><img src="/res/img/search_result/logo.png" alt="<?php print t('Home'); ?>" /></a>
                <?php endif; ?>
            </span>
            <div class="search_bar">
        		<?php if ($page['content_overlap']): ?>
                    <?php $hidden_text=True;?>
                    <?php print render($page['content_overlap']); ?>
                <?php endif; ?>
			</div>
            <div class="clearfix" ></div>
        </div>
        <div class="fixed_content" id="fixed_content">

            
            <div class="map_content" id="map_content">
                <div id="mapContainer" class="map_display"></div>

            </div>
            <div class="slide_btn slide_btn_s1" id="slide_btn_wrap">
                <button class="btn btn-default" id="slide_btn" ></button>
            </div>
            <div class="clearfix" style="position:relative;z-index:-1024;"></div>
            <div class="advertisement">
                <?php if ($page['advertisement_1']): ?>
                    <?php print render($page['advertisement_1']); ?>
                <?php endif; ?>
            </div>

            
        </div>
        <div id="content_container" class="real_content">
            
            <div class="filter">
                
                <ul class="nav nav-tabs"  id="categories_id" data-tabs="tabs">
                    <?php 
                    if (array_key_exists("target",$categories_data[0]))
                    {
                    ?>
                        <li><a href="#category_0" data-toggle="tab" enable_img="<?=$categories_data[0]["Enable_Img"]?>" disable_img="<?=$categories_data[0]["Disable_Img"]?>" category_index="<?=$categories_data[0]["Category_ID"]?>" "><div><img src="<?=$categories_data[0]["Enable_Img"]?>"/><span><?=$categories_data[0]["Category"]?>(<?=$categories_data[0]["Total"]?>)</span></div></a></li>
                    <?php
                    }
                    else
                    {
                        foreach ($categories_data as $index=>$category)
                        {
                            if ($category["Total"] > 0)
                            {
                    ?>    
                                <li><a href="#category_<?=$index?>" data-toggle="tab" enable_img="<?=$category["Enable_Img"]?>" disable_img="<?=$category["Disable_Img"]?>" category_index="<?=$category["Category_ID"]?>" "><img src="<?=$index==0?$category["Enable_Img"]:$category["Disable_Img"]?>"/><?=$category["Category"]?>(<?=$category["Total"]?>)</a></li>
                    <?php
                            }
                        }
                    }
                    ?>
                    <div class="navbar-right">
                        <div>
                        <div class="pull-left" style="margin:0 5px 0 0; line-height:55px;"><span style="font-weight:bold;color:#F00;" id="current_page_status">1</span>/<span id="max_page_status"><?=$categories_data[0]["Records"][0][0][2]?></span> </div>
                        <div class="input-group pull-right">
                        <button  type="button" class="btn btn-default btn_prev disabled" id="move_left"></button>
                        <button  type="button" class="btn btn-default btn_next  <?=$categories_data[0]["Records"][0][2] == 1? "disabled":""?>" id="move_right"> </button>
                        </div>
                        <div class="clearfix"></div>
                        </div>
                    </div>
                </ul>
                <div class="tab-content">
                <?php
                    foreach ($categories_data as $index=>$category)
                    {
                        if ($category["Total"] > 0)
                        {
                ?>
                        <div class="tab-pane fade" id="category_<?=$index?>">
                            <!-- filter here-->
                             <div id="filter_box">
                                <span class="icon"><span><?=$result_subset_filter?>:</span></span>
                                <?php require_once($_SERVER['DOCUMENT_ROOT']."/view/{$category["Filter"]}.filter.php")?>
                                <div class="clearfix"></div>
                             </div>
                                            
                            <div id="entity_content">
                        <?php 
                            $category_data = $category["Records"][0][0][0];
                            require_once($_SERVER['DOCUMENT_ROOT']."/view/{$category["Visual"]}.visual.php");?>
                            <div class="clearfix"></div>
                           </div>
                        </div>
                        <?php
                        }
                            ?>

                <?php
                    }
                    
                ?>
                    
                </div>
            </div>
                    <div class="footer" id="map_footer">
                <?php if ($page['footer']): ?>
                    <?php print render($page['footer']); ?>
                <?php endif; ?>
                </div>
        </div>
        </div>

